package app

import (
	"fmt"
	"im/model"
	"im/service"
	"im/util"
	"log"
	"math/rand"
	"net/http"
	"strconv"
)

var UserService service.UserService

func UserLogin(writer http.ResponseWriter, request *http.Request) {
	//解析参数
	err := request.ParseForm()
	if err != nil {
		log.Println(err.Error())
	}
	//接收参数
	mobile := request.PostForm.Get("mobile")
	password := request.PostForm.Get("password")

	user,err := UserService.UserLogin(mobile,password)

	if nil!= err {
		util.RespFail(writer,err.Error())
	} else {
		util.RespOK(writer,user,"成功")
	}
}

func UserRegister(w http.ResponseWriter, r *http.Request)  {
	err := r.ParseForm()
	if nil != err {
		log.Fatal(err.Error())
	}
	//接收参数
	mobile   := r.PostForm.Get("mobile")
	password := r.PostForm.Get("password")
	nickname := fmt.Sprintf("user%06d",rand.Int31n(10000))
	avater   := ""
	sex      := model.SEX_UNKNON
	user,err := UserService.Register(mobile,password,nickname,avater,sex)
	if nil != err {
		util.RespFail(w,err.Error())
	} else {
		util.RespOK(w,user,"成功")
	}
}

func FindUser(w http.ResponseWriter, r *http.Request)  {
	err := r.ParseForm()
	if nil != err {
		log.Fatal(err.Error())
	}
	//接收参数
	id := r.PostForm.Get("id")
	userId ,_ := strconv.ParseInt(id,10,64)
	userData := UserService.GetToken(userId, true)
	util.RespOK(w,userData,"成功")
}
